package com.mhc.suzuki.service.impl;

import com.aliyun.oss.OSSClient;
import com.mhc.suzuki.constant.AnnexGroupEnum;
import com.mhc.suzuki.constant.OssConfig;
import com.mhc.suzuki.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URL;
import java.util.Date;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class OssServiceImpl implements OssService {

    @Autowired
    private OssConfig ossConfig;
    @Override
    public String getUrl(Integer annexGroup, String name) {
        String endpoint = ossConfig.getEndpoint();
        String accessId = ossConfig.getAccessId();
        String accessKey = ossConfig.getAccessKey();
        String bucket = ossConfig.getBucket();
        String key = AnnexGroupEnum.getAnnexGroupEnum(annexGroup).toString().toLowerCase() + "/" + name;

        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try {
            long expireTime = ossConfig.getUploadExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            URL url = client.generatePresignedUrl(bucket, key, expiration);
            return url.toString();
        }catch (Exception e) {
            log.error("error in getUrl", e);
        } finally {
            // 关闭client
            client.shutdown();
        }
        return "";
    }
}
